<!-- 长列表 -->
<template>
  <div>
    <!-- 内容 -->
    <slot />
    <div ref="loadingTarget" class="h-6 py-4">
      <!-- 加载更多 -->
      <m-svg-icon
        v-show="loading"
        class="w-4 h-4 mx-auto animate-spin"
        name="infinite-load"
      ></m-svg-icon>
      <!-- 没有更多数据 -->
      <p v-if="isFinished" class="text-center text-base text-zinc-400">
        已经没有更多数据了
      </p>
    </div>
  </div>
</template>

<script setup>
import { ref } from '@vue/reactivity'
import { watch } from '@vue/runtime-core'
import { useIntersectionObserver, useVModel } from '@vueuse/core'

const props = defineProps({
  // 是否处于加载状态
  modelValue: {
    type: Boolean,
    required: true
  },
  // 数据是否全部加载完成
  isFinished: {
    type: Boolean,
    default: false
  }
})

const emits = defineEmits(['onLoad', 'update:modelValue'])

// 用来判断是否滚动到底部的元素
const loadingTarget = ref(null)

// 记录当前是否到底部
const targetIsIntersecting = ref(false)

useIntersectionObserver(loadingTarget, ([{ isIntersecting }]) => {
  // 加载更多可见 继续加载
  targetIsIntersecting.value = isIntersecting
  emitLoad()
})

// 触发load时间
const emitLoad = () => {
  setTimeout(() => {
    if (targetIsIntersecting.value && !loading.value && !props.isFinished) {
      // 修改加载数据标记
      loading.value = true
      // 触发更多加载行为
      emits('onLoad')
    }
  }, 100)
}

// 处理loading状态
const loading = useVModel(props)

watch(loading, emitLoad)
</script>
<style lang="scss" scoped></style>
